/**
 * @Time    : 2021/5/31 14:06
 * @Author  : Rich Chen
 * @License : Software business license
 * @Site    : www.rich-f.com
 * @File    : checkPassword.js
 * @Software: Rich Web Platform
 * @Function: 验证用户密码
 * @Version : 1.0
 **/

let logger = require('log4js').getLogger("default");
const {buildErrObject} = require('../../../utils/buildErrObject');
const moment = require('moment')

const checkPassword = function(password = '', user = {}) {
    return new Promise((resolve, reject) => {
        if (password === user.password){
            user.error_password_times = 0
            user.save((err, item) => {
                if (err) {
                    reject({code: 422,message: err.message, status: false})
                }
                resolve(item)
            })
            resolve(true)
        }else{
            logger.error('密码验证错误，请检查输入是否正确');
            user.error_password_times++
            if (user.error_password_times <= process.env.LOGIN_ATTEMPTS) {
                let login_attempts = process.env.LOGIN_ATTEMPTS - user.error_password_times
                user.save((err, item) => {
                    if (err) {                
                        console.log(err)
                        reject({code: 422,message: err.message, status: false})
                    }
                    resolve(item)
                })
                return reject(buildErrObject(422, '密码验证错误，还剩下' + login_attempts + '次登录，错误超过' + process.env.LOGIN_ATTEMPTS + '次后将锁定账号'))
            }else{
                user.error_password_times = 0
                user.lock_expire = moment(new Date()).add(process.env.HOURS_TO_BLOCK, 'h')
                user.save((err, item) => {
                    if (err) {
                        reject({code: 422,message: err.message, status: false})
                    }
                    resolve(item)
                })
                return reject(buildErrObject(409, '用户已锁定'))
            }

        }
    });
};

module.exports = {checkPassword}




